<?php

namespace app\award;

use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductAreaList;
use app\models\SetProductCommission;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\models\UserBalance;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class Award
{
    protected $user;
    protected $order;
    protected $set;

    protected $items;

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->user = User::findOne(['id' => $order->user_id]);
        $this->set = SetUserUp::getLastOne();

        // item list
        $this->items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        // 报单区才有奖
        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPORT'])) {
            $this->recommend();
        }

        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['R'])) {
            $this->recommend();

            $this->saveCommission2($this->user->id, $this->order->total_pay, 88, '充值');
        }

        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPEAT'])) {
            $this->diff();
        }
    }

    // 推荐奖
    protected function recommend()
    {
        $total_price = $this->order->total_pay - $this->order->total_freight;
        $r = Chain::getReferrer($this->order->user_id, true);
        if (!$r) {
            return;
        }

        $amount1 = (float)UserLevel::find()
            ->where(['value' => UserLevel::$keys['vip1']])
            ->select(['price'])
            ->scalar();
        $amount3 = (float)UserLevel::find()
            ->where(['value' => UserLevel::$keys['vip3']])
            ->select(['price'])
            ->scalar();

        if ($total_price == $amount1) {
            // 直推
            $commission = $this->set->r1;
            $this->saveCommission($r->id, $commission, '100', '直推');

            // 间推
            $r2 = $this->getIndirect($r->id);
            if ($r2) {
                $commission = $this->set->r2;
                $this->saveCommission($r2->id, $commission, '200', '间推');
            }
        }

        if ($total_price == $amount3) {
            if ($r->level == UserLevel::$keys['vip3']) {
                $commission = $this->set->r3;
                $this->saveCommission($r->id, $commission, '101', '直推');
            }
        }
    }

    // 复购奖
    protected function diff()
    {
        $award_name = '差价';
        $award_type = 40;

        $diff_vip1 = 0;
        $diff_vip2 = 0;
        $diff_vip3 = 0;

        $has_vip1 = false;
        $has_vip2 = false;
        $has_vip3 = false;

        $chain = Chain::getReferrerChain($this->order->user_id, [], true);

        foreach ($chain as $user) {
            if ($user->level <= $this->user->level) {
                continue;
            }


            if ((!$has_vip1 && !$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip1']) {
                $diff_vip1 = $this->_diff('diff_vip1');
                // var_dump($diff_vip1);exit;
                $this->saveCommission($user->id, $diff_vip1, $award_type, $award_name);
                $has_vip1 = true;
            }
            if ((!$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip2']) {
                $diff_vip2 = $this->_diff('diff_vip2');
                $diff_vip2 -= $diff_vip1;
                // var_dump($diff_vip2);exit;
                $this->saveCommission($user->id, $diff_vip2, $award_type, $award_name);
                $has_vip2 = true;
            }
            if ((!$has_vip3) && $user->level == UserLevel::$keys['vip3']) {
                $diff_vip3 = $this->_diff('diff_vip3');
                $diff_vip3 -= $diff_vip2 + $diff_vip1;
                $this->saveCommission($user->id, $diff_vip3, $award_type, $award_name);
                $has_vip3 = true;
                break;
            }
        }
    }

    private function _diff($diff_key)
    {
        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $sum = 0;
        foreach ($order_items as $item) {
            $product = SetProductCommission::findOne(['product_id' => $item->product_id])->toArray();
            $sum += ($item['price'] - $product[$diff_key]) * $item['quantity'];
        }

        return $sum;
    }

    // 团队奖
    protected function team()
    {
        $total_price = $this->order->total_pay - $this->order->total_freight;
        $award_name = '团队奖';
        $award_type = 200;

        $diff_vip2 = 0;
        $diff_vip3 = 0;
        $diff_vip4 = 0;

        $has_vip2 = false;
        $has_vip3 = false;
        $has_vip4 = false;

        $chain = Chain::getReferrerChain($this->order->user_id, [], true);

        foreach ($chain as $user) {
            if ((!$has_vip2 && !$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip2']) {
                $diff_vip2 = $total_price * Param::$t_vip2;
                $this->saveCommission($user->id, $diff_vip2, $award_type, $award_name);
                $has_vip2 = true;
            }
            if ((!$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip3']) {
                $diff_vip3 = $total_price * Param::$t_vip3;
                $diff_vip3 -= $diff_vip2;
                $this->saveCommission($user->id, $diff_vip3, $award_type, $award_name);
                $has_vip3 = true;
            }
            if ((!$has_vip4) && $user->level == UserLevel::$keys['vip4']) {
                $diff_vip4 = $total_price * Param::$t_vip4;
                $diff_vip4 -= $diff_vip3 + $diff_vip2;
                $this->saveCommission($user->id, $diff_vip4, $award_type, $award_name);
                $has_vip4 = true;
                break;
            }
        }
    }

    // 分红
    protected function profit()
    {
        $total_price = $this->order->total_pay - $this->order->total_freight;

        $vip3 = Chain::getReferrerChain($this->order->user_id, [UserLevel::$keys['vip3']]);
        $vip4 = Chain::getReferrerChain($this->order->user_id, [UserLevel::$keys['vip4']]);

        if ($vip3) {
            $commission = $total_price * Param::$p_vip3;
            $commission /= count($vip3);
            foreach ($vip3 as $user) {
                $this->saveCommission($user['id'], $commission, 30, '分红');
            }
        }

        if ($vip4) {
            $commission = $total_price * Param::$p_vip4;
            $commission /= count($vip4);
            foreach ($vip4 as $user) {
                $this->saveCommission($user['id'], $commission, 31, '分红');
            }
        }

    }


    // 拿间推的人
    private function getIndirect($user_id)
    {
        $the_referrer = Chain::getReferrer($user_id, true);
        if (!$the_referrer) {
            return null;
        }

        // 高等级 vip3
        if ($the_referrer->level > UserLevel::$keys['vip2']) {
            return $the_referrer;
        }

        // 处理两线条
        if ($the_referrer->level >= UserLevel::$keys['vip2']) {

            // 判断是否属于前2个直推
            $children = Chain::getChildrenSort($the_referrer->id, ['id']);

            // if (count($children) > $this->set->vip2) {
            if (count($children) > 2) {
                $children = [$children[0], $children[1]];
                $in = in_array($user_id, $children);
                if (!$in) {
                    return $the_referrer;
                } else {
                    return $this->getIndirect($the_referrer->id);
                }
            } else {
                return $this->getIndirect($the_referrer->id);
            }
        }

        return $this->getIndirect($the_referrer->id);
    }


    // 保存佣金
    protected function saveCommission($user_id, $balance, $type, $name)
    {
        if ($balance >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $this->order->user_id;
            $model->order_id = $this->order->id;
            $model->balance = $balance;
            $model->status = 1;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {

                // balance logs
                UserBalance::addLog($user_id,
                    $account->balance, $balance, $account->balance + $balance, '返佣', $this->order->id);


                $account->balance += $balance;
                $account->save();
            }
        }
    }

    protected function saveCommission2($user_id, $balance, $type, $name)
    {
        if ($balance >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $this->order->user_id;
            $model->order_id = $this->order->id;
            $model->platform_ticket = $balance;
            $model->status = 1;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {

                $account->platform_ticket += $balance;
                $account->save();
            }
        }
    }
}